function getTopics() {
    return new Promise(function (resolve, reject) {
        const url = '/api/topic';
        fetch(`${url}`, {
            method: 'get',
            headers: new Headers({
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${localStorage.getItem('token')}`
            })
        })
            .then((res) => {
                return res.json();
            })
            .then((res) => {
                resolve(res);
            }).catch(function (err) {
                reject(err);
            });
    });
}

async function showTopic() {
    const topics = JSON.parse(xss(JSON.stringify(await getTopics())));
    
    if (topics.ok) {
        let [canInnerHTML, mainInnerHTML] = ['', ''];

        const [can, main] = [
            document.querySelector('.can'),
            document.querySelector('.main')
        ];
        for (let i = 0, j = 1; i < topics.data.length; i++ , j++) {
            canInnerHTML += `<a class="header__info__nav__link" href="#${j}">${j}</a>`;
            mainInnerHTML +=
                `<div class="main__topic" id="${j}">
                    <h1 class="main__topic__number">第${j}题</h1>
                    <h1 class="main__topic__score">${topics.data[i].score}分</h1>
                    <p class="main__topic__question">${topics.data[i].question.replace(/\n/g, '<br />')}</p>
                    <form class="main__topic__form">
                        <input type="hidden" name="topicid" value="${topics.data[i]._id}" />
                        <input class="main__topic__form__answer" type="text" name="answer" placeholder="请输入您的答案" required autocomplete="off" />
                        <input class="main__topic__form__button" type="submit" value="提交答案" />
                    </form>
                </div>`;
        }
        can.innerHTML = canInnerHTML;
        main.innerHTML = mainInnerHTML;
        addSubmitAnswer();
    } else {
            alert('您还没有登录');
            window.location.href = '/html/user/login.html';
    }
}

function showInfo() {
    const token = localStorage.getItem('token');
    if (token === null) {
        alert('您还没有登录');
        window.location.href = '/html/user/login.html';
        return;
    }
    const infoJSON = JSON.parse(xss(Base64.decode(token.split('.')[1])));
    document.querySelector('.header__info__name').innerHTML = `${infoJSON.admin ? '管理员 ' : ''}${infoJSON.name}`;
}

function addSubmitAnswer() {
    const submit = document.querySelectorAll('.main__topic__form');
    for (let i = 0; i < submit.length; i++) {
        submit[i].addEventListener('submit', function (event) {
            event.preventDefault();
            this.elements[2].value = '正在提交中';
            const url = '/api/answer';
            fetch(`${url}`, {
                method: 'put',
                headers: new Headers({
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${localStorage.getItem('token')}`
                }),
                body: xss(JSON.stringify(serializeJSON(submit[i])))
            })
                .then((res) => {
                    return res.json();
                })
                .then((res) => {
                    if (res.ok) {
                        this.elements[2].value = res.msg;
                    } else {
                        this.elements[2].value = res.msg;
                    }
                });
        });
    }
}

showInfo();
showTopic();
